exports.msgCtrl = (function(){
    var ws = require('node-websocket-server/lib/ws/server');
    var server = ws.createServer();
    var sysMessage = [];
    var girls = [
            ['้',''],
            ['色情','ooxx'],
            ['GFW','404'],
            ['毛泽东','敬爱的毛爷爷']
        ];
    var msgRegs = [];
    var initMsgRegs = function(){
        for (var i = 0;i < girls.length;i++){
            try{
                msgRegs.push([new RegExp(girls[i][0], 'g'), girls[i][1]]);
            }catch(e){
                ;
            }
        }
    };
    initMsgRegs();
    var ips = {
        '0.0.0.0':{
            'recv':true,
            'send':true,
            'join':true
        }
    };
    var noah = {
        'ymac':'yctnbl'
    };
    var manager = [];
    var _channel = null;
    /*************************/
    var port = 10086;
    var response = {};
    var post2Admin = function(text, session){
        if (!text || !session)
            return false;
        for (var i = 0;i < manager.length; i++){
            try{
                manager[i].send(JSON.stringify({
                    'target':'newMessage',
                    'data':{
                        'text':text,
                        'timestamp':session.timestamp,
                        'ip':session._ip,
                        'nick':session.nick
                    }
                }));
            }catch(e){
                console.log('send2admin error', e.message);
            }
        }
    };
    var sysInfo = setInterval(function(){
        if (!_channel)
            return;
        for (var i = 0;i < manager.length; i++){
            try{
                manager[i].send(JSON.stringify({
                    'target':'sysInfo',
                    'data':{
                        'mem':process.memoryUsage().rss / 1024/1024,
                        'online':_channel.online,
                        'maxOnline':_channel.maxOnline
                    }
                }));
            }catch(e){
                console.log('sysInfo', e.message);
            }
        }
    }, 5000);
    server.addListener("connection", function(conn){
        var admin = false;
        console.log('admin...');
        conn.addListener("message", function(message){
            try{
                message = JSON.parse(message);
            }catch(e){
                message = {};
            }
            //console.log(message);
            if (!admin && message.target != 'login'){
                console.log('illegal key');
                conn.close();
                return;
            }
            
            switch(message.target){
                case 'login':
                    if (typeof noah[message.name] != 'undefined' && noah[message.name] == message.key){
                        if (!admin){
                            admin = true;
                            manager.push(conn);
                            conn._nick = 'admin';
                            console.log('login success');
                            response = {
                                code:true,
                                _msgId: message._msgId
                            };
                            conn.send(JSON.stringify(response));
                        }
                    }else{
                        console.log('illegal key');
                        conn.close();
                        return;
                    }
                break;
                
                case 'sysMessage':
                    /*
                    sysMessage.push({
                        'text':message.text,
                        'timestamp':new Date(),
                        'ip':'1.1.1.1',
                        'nick':conn._nick,
                        'sys':1
                    });
                    */
                    if (_channel){
                        that.newMessage(encodeURIComponent(message.text),{
                            'timestamp':new Date(),
                            'ip':'0.0.0.0',
                            'nick':conn._nick
                        });
                        _channel.appendMessage(conn._nick, "sysMsg", encodeURIComponent(message.text));
                    }
                break;
                
                case 'getIpBlock':
                    response = {
                        code:true,
                        ips: ips,
                        _msgId: message._msgId
                    };
                    conn.send(JSON.stringify(response));
                break;
                
                case  'addIpBlock':
                    response = {
                        status:that.addIpBlock(message.ip, message.type),
                        _msgId: message._msgId
                    };
                    conn.send(JSON.stringify(response));
                break;
                
                case 'removeIpBlock':
                    response = {
                        status:that.removeIpBlock(message.ip, message.type),
                        _msgId: message._msgId
                    };
                    conn.send(JSON.stringify(response));
                break;
            }
        });
        conn.addListener("close", function(){
            
            for (var i = manager.length - 1;i >= 0;i--){
                if (manager[i] == conn){
                    manager.splice(i, 1);
                }
            }
        });
    });
    var loadConfig = function(){
        
    };
    loadConfig();
    var that = {
        newMessage: function(msg, session){
            post2Admin(msg, session);
        },
        checkJoin: function(session){
            if (!session._ip || !ips[session._ip]){
                return true;
            }
            if (!ips[session._ip].join)
                return false;//明确定义不允许
            return true;
        },
        checkSend: function(msg, session){
            if (session._ip && ips[session._ip] && !ips[session._ip].send)
                return '';//明确定义不允许
            msg = msg.slice(0,30);
            for (var i = 0;i < msgRegs.length; i++){
                msg = msg.replace(msgRegs[i][0],msgRegs[i][1]);
            }
            return msg;
        },
        checkRecv: function(session){
            if (!session._ip || !ips[session._ip]){
                return true;
            }
            if (!ips[session._ip].recv)
                return false;//明确定义不允许
            return true;
        },
        getIpBlock: function(){
            
        },
        addIpBlock: function(ip, type){
            console.log('addIpBlock',!ip,!type,type != 'recv' ,type != 'send');
            if (!ip || !type || (type != 'recv' && type != 'send' && type != 'join'))
                return false;
            if (!ips[ip])
                ips[ip] = {
                    'recv':true,
                    'send':true,
                    'join':true
                };
            ips[ip][type] = false;
            //console.log('-->>',ips);
            return true;
        },
        removeIpBlock: function(ip, type){
            console.log('addIpBlock',ip, type,!ip,!type,type != 'recv' ,type != 'send');
            if (!ip || !type || (type != 'recv' && type != 'send' && type != 'join'))
                return false;
            if (!ips[ip])
                ips[ip] = {
                    'recv':true,
                    'send':true,
                    'join':true
                };
            ips[ip][type] = true;
            return true;
        },
        getKeyBlock: function(){},
        addKeyBlock: function(){},
        removeKeyBlock: function(){},
        logMsg: function(message, session){
        
        },
        shiftSysMessage: function(){
            return sysMessage.shift();
        },
        setChannel: function(ch){
            _channel = ch;
        },
        saveConfig: function(){
            
        },
        loadConfig: function(){
            
        }
    };
    
    server.listen(port);
    console.log('admin@', port);
    return that;
})();